<?php
namespace app\models;

use yii\db\ActiveRecord;

/**
 * 广告位置
 *
 * Class AdLocation
 * @package app\models
 *
 * @property integer $id
 * @property integer $type
 * @property string $name
 * @property integer $max_count
 * @property integer $width
 * @property integer $height
 * @property string $code
 * @property string $remark
 *
 * @property array activeAdList 当前可用广告列表的查询条件
 */
class AdLocation extends ActiveRecord
{
    const TYPE_TEXT = 1;
    const TYPE_IMAGE = 2;

    /**
     * @inheritDoc
     */
    public function rules()
    {
        return [
            [['type', 'name'], 'required'],
            [['type', 'max_count', 'width', 'height'], 'integer'],
            ['name', 'string', 'max'=>32],
            [['code', 'remark'], 'safe'],
        ];
    }
    
    /**
     * 返回当前可用的广告查询条件
     * @return \yii\db\ActiveQuery
     */
    public function getActiveAdList()
    {
        $query = $this->hasMany(Ad::className(), ['lid'=>'id'])
            ->andWhere(['status'=>Ad::STATUS_ACTIVE])
            ->andWhere(['<=', 'start_time', time()])
            ->andWhere(['>=', 'end_time', time()])
            ->orderBy('id DESC');
        if ($this->max_count > 0) {
            $query->limit($this->max_count);
        }
        return $query;
    }
}
